<template>
  <div class="loginDivMain">
    <div class="loginDiv">
      <span class="loginSpan">用户登录</span>
      <div>
        <span>用户名：</span>
        <el-input v-model="userName" style="width: 240px" placeholder="请输入用户名" />
      </div>
      <div class="passwordDiv">
        <span>密 &nbsp; 码：</span>
        <el-input
          v-model="password"
          style="width: 240px"
          placeholder="请输入密码"
          type="password"
        />
      </div>
      <div>
        <el-button class="loginButton" @click="login" type="primary" round>登录</el-button>
        <el-link class="registerLink" type="primary" @click="register"
          >没有账号？立即注册！</el-link
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../stores/userStore'
import { ElMessage } from 'element-plus'
import myAxios from '../../axios/myAxios'
const router = useRouter()

const userName = ref('')
const password = ref('')
const user = useUserStore()
const login = () => {
  myAxios
    .post('/user/login', {
      username: userName.value,
      password: password.value,
    })
    .then((res) => {
      if (res.data.code === 200) {
        localStorage.setItem('token', res.data.data.token)
        user.setUserInfo({
          id: res.data.data.user.id,
          name: res.data.data.user.username,
          password: res.data.data.user.password,
          email: res.data.data.user.email,
          phone: res.data.data.user.phone,
          role: res.data.data.user.role,
        })
        router.push('/home')
      } else {
        ElMessage({
          message: '用户名或密码错误',
          type: 'error',
        })
      }
    })
}
const register = () => {
  router.push('/register')
}
</script>

<style scoped>
.loginDivMain {
  height: 100%;
  width: 100%;
  background-image: url(../../assets/登录背景图.jpg);
  background-size: cover;
}
.loginDiv {
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  flex-direction: column;
  align-items: center;
  height: 65%;
  width: 40%;
  row-gap: 40px;
  background-color: white;
  border: 1px solid #fff;
  border-radius: 10%;
}

.loginSpan {
  font-size: 20px;
  margin-top: 40px;
}

.loginButton {
  width: 120px;
}

.registerLink {
  position: absolute;
  font-size: 8px;
  margin-top: 16px;
  margin-left: 15px;
}
</style>
